﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dominio;
using NHibernate;
using NHibernate.Linq;
using NHibernate.Criterion;

namespace Repositorio
{
    public class RepositorioBasico<T>:IRepositorioBasico<T> where T:EntidadeBasica
    {
        public void Salvar(T entidade)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        session.SaveOrUpdate(entidade);
                        transaction.Commit();
                    }
                    catch(Exception ex)
                    {
                        transaction.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public T SelecionarPorId(long id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.Get<T>(id);
        }

        public IEnumerable<T> Listar()
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session
                    .QueryOver<T>()
                    .List<T>();
        }

        public IEnumerable<T> Listar(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session
                    .QueryOver<T>()
                    .Where(predicate)
                    .List<T>();
        }

    }
}
